<?php
// +----------------------------------------------------------------------
// | Description: 角色员工关系
// +----------------------------------------------------------------------
// | Author:
// +----------------------------------------------------------------------

namespace app\admin\model;

use app\admin\model\Common;
use think\facade\Db;


/**
 * Class Access
 * @package app\admin\model
 * @author Mr.Li
 * @create 2021-06-02 11:56
 */
class Access extends Common
{
    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */

    protected $name = 'admin_access';

    public function dataAuth()
    {
        return $this->hasOne(DataAuthModel::class, 'group_id','group_id')->field('group_id,market');
    }

    /**
     * [getDataList 获取列表]
     * @param $user_id
     * @param $groups
     * @param string $action
     * @return bool
     * @author Mr.Li
     * @create 2021-06-02 11:58
     */
    public function userGroup($user_id, $groups, $action = '')
    {
        if (!$user_id) {
            $this->error = '参数错误';
            return false;
        }
        $this->startTrans();
        try {
            if ($action == 'update') {
                $this->where('user_id', $user_id)->delete();
            }
            foreach ($groups as $k => $v) {
                if (!Db::name('admin_access')->where(['user_id' => $user_id,'group_id' => $v])->find()) {
                    $userGroup['user_id'] = $user_id;
                    $userGroup['group_id'] = $v;
                    $userGroups[] = $userGroup;
                }
            }
            $this->saveAll($userGroups);
            $this->commit();
            return true;
        } catch(\Exception $e) {
            $this->rollback();
            $this->error = '编辑失败';
            return false;
        }
    }
    /**
     * 获取用户数据权限
     * @author ran
     * @date 2021-11-05 14:17
     * mailbox 466180170@qq.com
     */
    public function getCommonUserDataAuth($userId)
    {
        $data = $this->where('user_id',$userId)->with('dataAuth')->find();
        if(!empty($data)){
            $data =$data->toArray();
            return $data['dataAuth'];
        }
        return [];
    }
}
